#! /usr/bin/env python3
# encoding: utf-8
"""
@file: views.py
@author: www.xcooo.cn
@Mail: 602006050@qq.com
"""
import time
from datetime import datetime, timedelta

from flask import abort
from flask import current_app, jsonify
from flask import g
from flask import redirect
from flask import render_template
from flask import request
from flask import session
from flask import url_for

from info import constants, db
from info.models import User, News, Category
from info.utils.captcha.image_storage import storage
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import admin_blu

@admin_blu.route('/news_category',methods = ['GET','POST'])
def news_category():
    '''
    新闻分类管理
    :return:
    '''
    if request.method == 'GET':
        # 1.获取新闻分类id
        try:
            categoies = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return render_template('admin/news_type.html', errmsg='查询数据错误')

        # 2.将列表对象转换成字典对象列表
        categoies_dict_li = []
        for category in categoies:
            # 取到分类的字典
            cate_dict = category.to_dict()
            categoies_dict_li.append(cate_dict)

        # 3.移除最新的分类
        categoies_dict_li.pop(0)

        data = {
            'categories': categoies_dict_li
        }

        return  render_template('admin/news_type.html',data=data)

    # 此处处理post请求(分类修改操作)
    # 1.获取参数
    cname = request.json.get('name')
    # 如果传了cid,代表是编辑分类名称
    cid = request.json.get('id')

    # 2.校验参数
    if not cname:
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # 3.有分类id查询对应的分类名(分类名编辑操作)
    if cid:
        try:
            cid = int(cid)
            category = Category.query.get(cid)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg="查询失败")
        category.name = cname

    # 4.没有分类id,初始化模型对象并赋值(增加分类操作)
    else:
        category = Category()
        category.name = cname
        db.session.add(category)

    # 5.返回成功的结果
    return jsonify(errno=RET.OK, errmsg="成功")


@admin_blu.route('/news_edit_detail',methods=['GET','POST'])
@user_login_data
def news_edit_detail():
    '''
    查询点击的新闻数据和传入到模板中
    :return:
    '''
    if request.method == 'GET':
        # 1. 获取参数
        news_id = request.args.get('news_id')

        # 2. 判断参数
        if not news_id:
            abort(404)

        try:
            news_id = int(news_id)
        except Exception as e:
            current_app.logger.error(e)
            return render_template('admin/news_edit_detail.html',errmsg='参数错误')

        # 3.通过id查询到新闻对象
        try:
            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)
            return render_template('admin/news_edit_detail.html',errmsg='查询失败')

        if not news:
            return render_template('admin/news_edit_detail.html', errmsg='新闻不存在')

        # 4.此时代表新闻已存在,查询新闻分类数据
        try:
            categoies = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return render_template('admin/news_edit_detail.html', errmsg='查询数据错误')

        # 5.将列表对象转换成字典对象列表
        categoies_dict_li = []
        for category in categoies:
            # 取到分类的字典
            cate_dict = category.to_dict()
            # 判断遍历当前的分类是否为当前新闻的分类
            if category.id == news.category_id:
                cate_dict['is_selected'] = True
            categoies_dict_li.append(cate_dict)

        # 移除最新的分类
        categoies_dict_li.pop(0)

        data = {
            'news':news.to_dict(),
            'categories':categoies_dict_li
        }

        return render_template('admin/news_edit_detail.html',data=data)

    # 此处使用post方式    处理新闻编辑提交请求

    # 1.获取参数
    news_id = request.form.get("news_id")
    title = request.form.get("title")
    digest = request.form.get("digest")
    content = request.form.get("content")
    index_image = request.files.get("index_image")
    category_id = request.form.get("category_id")

    # 2.判断数据是否有值
    if not all([title, digest, content, category_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # 3.通过 新闻id查询到指定的新闻
    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询失败")

    if not News:
        return jsonify(errno=RET.NODATA, errmsg="新闻不存在")

    # 4.先尝试读取图片,将图片上传到七牛云.得到一个 key
    if index_image:
        try:
            index_image = index_image.read()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

        try:
            key = storage(index_image)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.THIRDERR, errmsg="上传图片失败")
        news.index_image_url = constants.QINIU_DOMIN_PREFIX + key

    # 5.此时新闻以存在,更新数据保存到数据库
    news.title = title
    news.digest = digest
    news.content = content
    news.category_id = category_id

    # 6.返回成功的结果
    return jsonify(errno=RET.OK, errmsg="编辑成功")


@admin_blu.route('/news_edit')
def news_edit():
    '''
       新闻版式的逻辑
       :return:
       '''
    # 1.获取到传入参数(取到url后面的参数)
    page = request.args.get('page', 1)
    keywords = request.args.get('keywords',None)

    # 2.判断参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    news_list = []
    current_page = 1
    total_page = 1

    filters = [News.status == 0]
    if keywords:
        # 如果关键字存在,就添加关键字搜索
        filters.append(News.title.contains(keywords))
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,
                                                                                          constants.ADMIN_NEWS_PAGE_MAX_COUNT,
                                                                                          False)
        current_page = paginate.page
        total_page = paginate.pages
        news_list = paginate.items  # 用户数据对象
    except Exception as e:
        current_app.logger.error(e)

    # 3.将模型列表转换为字典列表
    news_dict_li = []
    for new in news_list:
        news_dict_li.append(new.to_basic_dict())

    data = {
        'news': news_dict_li,
        'current_page': current_page,
        'total_page': total_page
    }
    return render_template('admin/news_edit.html', data=data)


@admin_blu.route('/news_review_action',methods=['POST'])
def news_review_action():
    '''
    新闻审核是否通过
    :return:
    '''
    # 1.前台使用ajax 后台获取参数(新闻id,方式,拒绝原因)
    news_id = request.json.get('news_id')
    action = request.json.get('action')

    # 2.校验参数
    if not all([news_id,action]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    if action not in(['accept','reject']):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 3.查询新闻对象
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='未查询到该新闻')

    if not news:
        return jsonify(errno=RET.NODATA, errmsg='不存在该新闻')

    # 4.此时新闻已存在,执行通过审核和拒绝审核的逻辑
    if action == 'accept':
        # 审核通过
        news.status = 0
    else:
        # 审核不通过(需要附带原因)
        reason = request.json.get('reason')
        if not reason:
            return jsonify(errno=RET.PARAMERR, errmsg='请输入拒绝原因')
        news.status = -1
        news.reason = reason

    # 5.返回成功的结果
    return jsonify(errno=RET.OK, errmsg='审核通过')


@admin_blu.route('/news_review_detail/<int:news_id>')
def news_review_detail(news_id):
    '''
    新闻审核的管理操作逻辑
    :return:
    '''
    # 通过id获取新闻模型对象
    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)

    # 判断新闻是否存在
    if not news:
        return render_template('admin/news_review_detail.html',data={'errmsg':'新闻不存在'})

    data = {
        'news':news.to_dict()
    }
    return render_template('admin/news_review_detail.html',data=data)

@admin_blu.route('/news_review')
def news_review():
    '''
    新闻审核的逻辑
    :return:
    '''
    # 1.获取到传入参数(取到url后面的参数)
    page = request.args.get('page', 1)
    keywords = request.args.get('keywords',None)

    # 2.判断参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    news_list = []
    current_page = 1
    total_page = 1

    filters = [News.status != 0]
    if keywords:
        # 如果关键字存在,就添加关键字搜索
        filters.append(News.title.contains(keywords))
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,constants.ADMIN_NEWS_PAGE_MAX_COUNT,False)
        current_page = paginate.page
        total_page = paginate.pages
        news_list = paginate.items  # 用户数据对象
    except Exception as e:
        current_app.logger.error(e)

    # 3.将模型列表转换为字典列表
    news_dict_li = []
    for new in news_list:
        news_dict_li.append(new.to_review_dict())

    data = {
        'news': news_dict_li,
        'current_page': current_page,
        'total_page': total_page
    }
    return render_template('admin/news_review.html',data=data)

@admin_blu.route('/user_list')
@user_login_data
def user_list():
    '''
   用户列表数据展示
    :return:
    '''
    # 1.获取到传入参数(取到url后面的参数)
    page = request.args.get('page',1)

    # 2.判断参数
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    user_list = []
    current_page = 1
    total_page = 1
    try:
        paginate = User.query.filter(User.is_admin==False).paginate(page,constants.ADMIN_USER_PAGE_MAX_COUNT,False)
        current_page = paginate.page
        total_page = paginate.pages
        user_list = paginate.items  # 用户数据对象
    except Exception as e:
        current_app.logger.error(e)

    # 3.将模型列表转换为字典列表
    user_dict_li = []
    for user in user_list:
        user_dict_li.append(user.to_admin_dict())

    data = {
        'user':user_dict_li,
        'current_page':current_page,
        'total_page':total_page
    }
    return render_template('admin/user_list.html',data=data)

@admin_blu.route('/user_count')
def user_count():
    '''
    统计用户的逻辑
    :return:
    '''
    # 1. 查询总人数(除管理员之外)
    total_count = 0
    try:
        total_count = User.query.filter(User.is_admin==False).count()
    except Exception as e:
        current_app.logger.error(e)

    # 2.月新增数
    mon_count = 0
    t = time.localtime()
    # 查询当月时间对象
    begin_mon_date = datetime.strptime(('%d-%02d-01' % (t.tm_year,t.tm_mon)),'%Y-%m-%d')
    try:
        mon_count = User.query.filter(User.is_admin == False,User.create_time > begin_mon_date ).count()
    except Exception as e:
        current_app.logger.error(e)

    # 3.日增加数
    day_count = 0
    t = time.localtime()
    begin_day_date = datetime.strptime(('%d-%02d-%02d' % (t.tm_year, t.tm_mon,t.tm_mday)), '%Y-%m-%d')
    try:
        day_count = User.query.filter(User.is_admin == False, User.create_time > begin_day_date).count()
    except Exception as e:
        current_app.logger.error(e)

    # 4.折线图可视化逻辑
    active_time = []
    active_count = []

    # 取到今天活跃的用户数量
    # 时间对象
    today_date = datetime.strptime(('%d-%02d-%02d' % (t.tm_year, t.tm_mon, t.tm_mday)), '%Y-%m-%d')

    for i in range(0,31):
        # 取出今天的0点0分
        begin_date = today_date - timedelta(days=i)
        # 取出今晚的0点0分
        end_date= today_date - timedelta(days=i-1)
        # print(end_date)
        count = User.query.filter(User.is_admin == False, User.last_login >= begin_date, User.last_login <= end_date).count()
        active_count.append(count)
        active_time.append(begin_date.strftime('%Y-%m-%d'))

    # 对时间和人数做反转操作
    active_time.reverse()
    active_count.reverse()

    # count = User.query.filter(User.is_admin == False, User.last_login >= 今天的0时0分,User.last_login <= 昨天的0时0分).count()
    data = {
        'total_count':total_count,
        'mon_count':mon_count,
        'day_count':day_count,
        'active_time':active_time,
        'active_count':active_count
    }
    return render_template('admin/user_count.html',data=data)

@admin_blu.route('/index')
@user_login_data
def admin_index():
    user = g.user
    data = {
        'user':user.to_dict()
    }
    return render_template('admin/index.html',data=data)

@admin_blu.route('/login',methods = ['GET','POST'])
def login():
    '''
    后台管理登陆界面
    :return:
    '''
    if request.method == 'GET':
        # 判断当前用户是否登陆,如果有登陆直接直接重定向到后台主页
        user_id= session.get('user_id',None)
        is_admin = session.get('is_admin',False)
        if user_id and is_admin:
            return redirect(url_for('admin.admin_index'))
        return render_template('admin/login.html')

    # 1. 获取参数(账号,密码)
    name = request.form.get('username')
    password = request.form.get('password')

    # 2. 判断参数
    if not all([name,password]):
        return render_template('admin/login.html',errmsg='请输入账号密码')

    # 3.查询用户是否存在
    try:
        user = User.query.filter(User.mobile == name,User.is_admin==True).first()
    except Exception as e:
        current_app.logger.error(e)
        return render_template('admin/login.html', errmsg='查询失败')

    if not user:
        return render_template('admin/login.html', errmsg='不存在该用户')

    # 4.校验密码
    if not user.check_password(password):
        return render_template('admin/login.html', errmsg='用户名或密码错误')

    # 5.保存用户信息
    session['user_id'] = user.id
    session['user_mobile'] = user.mobile
    session['user_name'] = user.nick_name
    session['is_admin'] = user.is_admin

    # 6.重定向到后台首页
    return redirect(url_for('admin.admin_index'))